import { request } from './request';

export interface TemuProductInfo {}

// 获取用户的信息,这个包括了相关的产品信息
export interface GetTemuUserInfoResult {
  // 如果是 true 表示成功
  success: boolean;
  // 如果是 1000000 表示成功
  errorCode: number;
  errorMsg: null | string;
  result: {
    userId: number;
    maskMobile: string;
    maskOwnerMobile: string;
    accountType: number;
    accountStatus: number;
    tokenType: number;
    companyList: {
      companyName: string;
      malInfoList: {
        mallId: number;
        mallName: string;
        logo: string;
        mallStatus: number;
        isSemiManagedMall: boolean;
      }[];
    }[];
    nickName: string;
    roleNameList: string[];
  };
}
export function getTemuUserInfo<T = GetTemuUserInfoResult>() {
  return request<T, T>({
    url: 'https://seller.kuajingmaihuo.com/bg/quiet/api/mms/userInfo',
    method: 'POST',
    data: {},
  });
}

// 分页查找产品信息
export interface PageQueryOptions {
  page: number;
  pageSize: number;
  skcTopStatus?: number;
  productIds?: number[];
}

export interface PageQueryResultPageItem {
  productId: number;
  productSkcId: number;
  productName: string;
  productType: number;
  sourceType: number;
  goodsId: number;
  leafCat: {
    catId: number;
    catName: string;
    catEnName: null;
    catType: number;
  };
  categories: {
    cat1: {
      catId: number;
      catName: string;
      catEnName: null;
      catType: null;
    };
    cat2: {
      catId: number;
      catName: string;
      catEnName: null;
      catType: null;
    };
    cat3: {
      catId: number;
      catName: string;
      catEnName: null;
      catType: null;
    };
    cat4: {
      catId: number;
      catName: string;
      catEnName: null;
      catType: null;
    };
    cat5: {
      catId: number;
      catName: string;
      catEnName: null;
      catType: null;
    };
    cat6: {
      catId: number;
      catName: string;
      catEnName: null;
      catType: null;
    };
    cat7: {
      catId: number;
      catName: string;
      catEnName: null;
      catType: null;
    };
    cat8: {
      catId: number;
      catName: string;
      catEnName: null;
      catType: null;
    };
    cat9: {
      catId: number;
      catName: string;
      catEnName: null;
      catType: null;
    };
    cat10: {
      catId: number;
      catName: string;
      catEnName: null;
      catType: null;
    };
    catType: number;
  };
  productProperties: {
    templatePid: number;
    pid: number;
    refPid: number;
    propName: string;
    vid: number;
    propValue: string;
    valueUnit: string;
    valueExtendInfo: string;
    numberInputValue: string;
  }[];
  sizeTemplateIds: null;
  productTotalSalesVolume: number;
  extCode: string;
  skcStatus: number;
  skcSiteStatus: number;
  mainImageUrl: string;
  last7DaysSalesVolume: null;
  productSkuSummaries: {
    productSkuId: number;
    thumbUrl: string;
    productSkuSpecList: {
      parentSpecId: number;
      parentSpecName: string;
      specId: number;
      specName: string;
      unitSpecName: null;
    }[];
    currencyType: string;
    financeExchangeRate: number;
    supplierPrice: null;
    supplierPriceUS: null;
    siteSupplierPrices: {
      siteId: number;
      supplierPrice: number;
      maxSupplierPrice: null;
    }[];
    extCode: string;
    productSkuWhExtAttr: {
      productSkuVolume: {
        len: number;
        width: number;
        height: number;
        inputLen: null;
        inputWidth: null;
        inputHeight: null;
        inputUnit: null;
      };
      productSkuWeight: {
        value: number;
        inputValue: null;
        inputUnit: null;
      };
      productSkuVolumeLabel: null;
      productSkuWmsVolume: null;
      productSkuWmsWeight: null;
      productSkuWmsVolumeLabel: null;
      productSkuBarCodes: null;
      productSkuSensitiveAttr: {
        isSensitive: number;
        sensitiveTypes: any[];
        sensitiveList: any[];
        isForce2Normal: boolean;
        force2NormalTypes: null;
      };
      productSkuSensitiveLimit: null;
      productSkuFragileLabelAttr: null;
      latestShippingModeEditRecord: null;
      productSkuSameReference: null;
    };
    productSkuSaleExtAttr: {
      productSkuCustomizationTmpl: null;
      productSkuShippingMode: number;
      productSkuAccessories: null;
      productSkuIndividuallyPacked: null;
      productSkuNetContent: null;
      productSkuStockDisplayOption: null;
    };
    todaySalesVolume: null;
    realStock: null;
    virtualStock: number;
    virtualStockLimitType: null;
    salesStockLockType: null;
    stockLockDetailList: null;
    tempLockNum: number;
    productSkuSemiManagedStock: {
      skuStockQuantity: number;
      tempLockNum: number;
      supportMultiWarehouse: null;
      disableQuantity: number;
      existShippingShelfRoute: boolean;
      existShippingCertWarehouseNoBinding: null;
      enablePreSale: boolean;
    };
    sampleNetWeight: null;
    productSkuCwVOList: null;
    productSkuMultiPack: {
      skuClassification: number;
      numberOfPieces: number;
      pieceUnitCode: number;
      individuallyPacked: null;
      productSkuNetContent: null;
    };
    priceReviewStatus: null;
    flowLimit: number;
    preLimitTime: null;
  }[];
  createdAt: number;
  productJitMode: {
    matchJitMode: boolean;
    quickSellAgtSignStatus: null;
    signLatestAgt: boolean;
  };
  productCertAuditStatus: null;
  offSaleByNoCert: null;
  noCertPunishRecord: null;
  productCertConfig: null;
  productCertPunish: null;
  productPersonalization: {
    personalizationSwitch: null;
    personalizationTmp: null;
    signLatestAgt: boolean;
    personalizationAgtSignStatus: null;
  };
  goodsAdvantageLabelVOList: null;
  productTags: null;
  productFragileLabelAttr: {
    isFragile: boolean;
  };
  productGuideFileI18nList: {
    fileName: string;
    fileUrl: string;
    fileUrlDisplay: null;
    languages: string[];
    instructionId: number;
    instructionSnapshotId: number;
    supplementId: null;
    sourceFileUrl: null;
    language: string;
  }[];
  productGuideFileNewVOList: any[];
  printedGuideFileInfoVO: null;
  productPropAdjustTasks: null;
  needGuideFile: boolean;
  productGuideFileIfNeed: number;
  guideFileStatus: number;
  guideFileFailReason: null;
  electronicGuideFileComplianceLabel: number;
  printedGuideFileComplianceLabel: number;
  productSelected: boolean;
  canEditSizeTemplate: null;
  inProcessEditTasks: null;
  productAuditDraft: null;
  hasDecoration: boolean;
  hasCarouseVideo: boolean;
  hasDetailVideo: null;
  matchSkcJitMode: boolean;
  isJitUnSignForMms: boolean;
  guideFileAttribute: null;
  similarClusterProduct: null;
  guideFilePageImages: {
    language: string;
    imgUrl: string;
  }[];
  isSupportPersonalization: boolean;
  supplierSourceType: number;
  productSemiManaged: {
    bindSites: {
      siteId: number;
      siteName: string;
      dr: string;
      matchSemiManaged: boolean;
      matchPreSemiHosting: boolean;
    }[];
    cwSupportBindSiteIds: null;
    semiLanguageStrategy: null;
    semiLanguageSiteMode: null;
    productShipment: {
      freightTemplate: {
        freightTemplateId: string;
        templateName: null;
        templateSubType: number;
        warehouseRegion1List: {
          code: number;
          name: string;
          shortName: string;
          chineseName: string;
        }[];
      };
      shipmentLimitSecond: number;
    };
  };
  productPublishLabel: null;
  productPattern: {
    canRelatePattern: boolean;
    patternId: null;
    isModified: null;
    garmentPreviewPics: null;
    paperPreviewPics: null;
    patternFile: null;
    modifiedPaperPreviewPics: null;
    modifiedPatternFile: null;
  };
  productCustomizationTechnology: null;
  hotSaleGoodsLabelStyle: number;
  sensitiveAttrProblemTag: boolean;
  classId: null;
  industrySelectionTag: boolean;
  allowanceCertList: null;
  flowAllowanceSiteList: null;
  flowAllowanceStatus: number;
  newProductCatMisplace: {
    matchMisplace: boolean;
    recCategoriesList: any[];
    feedback: null;
  };
  productPotentialInfo: {
    matchPotentialProduct: boolean;
    sitePotentialInfoList: any[];
  };
  hotSaleCarouselVideoNeedUpload: boolean;
  highPrice: boolean;
}

export interface PageQueryResult {
  success: boolean;
  errorCode: number;
  errorMsg: null | string;
  result: {
    total: number;
    pageItems: Array<PageQueryResultPageItem>;
  };
}
export function pageQuery<T = PageQueryResult>(options: PageQueryOptions, mallId: number) {
  if (options.skcTopStatus === 1000) {
    delete options.skcTopStatus; // 删除 skcTopStatus 属性
  }
  return request<T, T>({
    url: 'https://agentseller.temu.com/visage-agent-seller/product/skc/pageQuery',
    method: 'POST',
    data: {
      ...options,
    },
    headers: {
      Mallid: mallId,
    },
  });
}

// 通过产品的 id 和 skcId 获取产品的云仓 id
export interface QueryBtgProductStockInfoResult {
  success: boolean;
  errorCode: number;
  errorMsg: null | string;
  result: {
    preSaleSkuLimitNumber: null;
    productStockList: Array<{
      productSkuId: number;
      preSaleStockDeliveryDay: null;
      advancedCoopWarehouseStockAvailable: number;
      enablePreSale: boolean;
      stockType: null;
      showPreSale: boolean;
      supportSwitchToSystemSync: null;
      warehouseStockList: Array<{
        warehouseInfo: {
          warehouseDisable: boolean;
          warehouseId: string;
          warehouseName: string;
          managementType: null;
        };
        warehouseDisable: boolean;
        inTransitPreSaleStock: null;
        stockAvailable: number;
        siteList: Array<{
          siteName: string;
          siteId: number;
          dr: null;
        }>;
      }>;
      shippingMode: number;
    }>;
  };
}
export function queryBtgProductStockInfo<T = QueryBtgProductStockInfoResult>({
  productId,
  productSkuId,
  mallId,
}: {
  productId: number;
  productSkuId: number;
  mallId: number;
}) {
  return request<T, T>({
    url: 'https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/starlaod/btg/sales/stock/queryBtgProductStockInfo',
    method: 'POST',
    data: {
      productId,
      productSkuIdList: [productSkuId],
    },
    headers: {
      Mallid: mallId,
    },
  });
}

// 更新库存,如果 currentStockAvailable 和当前最新库存不匹配会导致更新失败。
export interface UpdateMmsBtgProductSalesStockResult {
  result: {
    skuMaxQuantityDTOList: null;
    failEnablePreSaleSkuList: null;
    isSuccess: boolean;
  };
  success: boolean;
  errorCode: number;
  errorMsg: null | string;
}
export function updateMmsBtgProductSalesStock<T = UpdateMmsBtgProductSalesStockResult>({
  productId,
  currentStockAvailable,
  productSkuId,
  stockDiff,
  warehouseId,
  mallId,
}: {
  productId: number;
  currentStockAvailable: number;
  productSkuId: number;
  stockDiff: number;
  warehouseId: string;
  mallId: number;
}) {
  return request<T, T>({
    url: 'https://seller.kuajingmaihuo.com/marvel-mms/cn/api/kiana/starlaod/btg/sales/stock/updateMmsBtgProductSalesStock',
    method: 'POST',
    data: {
      productId: productId,
      skuStockChangeList: [
        {
          productSkuId: productSkuId,
          stockDiff: stockDiff,
          currentStockAvailable: currentStockAvailable,
          currentShippingMode: 1,
          warehouseId: warehouseId,
        },
      ],
      skuTypeChangeList: [],
      isCheckVersion: true,
      source: 0,
    },
    headers: {
      Mallid: mallId,
    },
  });
}

// 获取报名活动信息
// {
//     "activityLabelDesc": null,
//     "activityContent": "清仓爆品限时疯抢，库存告急！成交链路全面沸腾！",
//     "sessionEndTime": null,
//     "activityLabelTag": null,
//     "activityName": "清仓进阶",
//     "sessionStartTime": null,
//     "thematicList": [
//         {
//             "canEnrollTotal": null,
//             "activityLabelDesc": "Deals额外享",
//             "enrollDeadLine": 1751353199000,
//             "activityLabelTag": 6,
//             "sites": [
//                 {
//                     "siteId": 100,
//                     "siteName": "美国站"
//                 },
//             ],
//             "activityThematicId": 2506080407645841,
//             "activityThematicContent": "清仓爆品限时疯抢，库存告急！成交链路全面沸腾！",
//             "durationDays": 8,
//             "benefitLabelName": [
//                 "清仓利器",
//                 "大流量"
//             ],
//             "enrollSource": 1,
//             "salePromotionLabel": null,
//             "enrollStartAt": 1749484800000,
//             "enrolledCount": 0,
//             "startTime": 1750680000000,
//             "endTime": 1751353199000,
//             "activityLabelList": [
//                 {
//                     "value": "Deals额外享",
//                     "key": 6
//                 }
//             ],
//             "activityThematicName": "月末狂欢专区（6月）"
//         },
//     ],
//     "autoAssignEndTime": null,
//     "autoAssignStartTime": null,
//     "benefitLabelName": [
//         "清仓利器",
//         "大流量"
//     ],
//     "sessionList": null,
//     "sessionAssignType": 2,
//     "sessionAggList": null,
//     "activityType": 127
// }
export interface GetActivityListResult {
  success: boolean;
  // 1000000 表示成功
  errorCode: number;
  errorMsg: null | string;
  result: {
    activityCarouselVOList: any[];
    activityList: Array<{
      activityLabelDesc: string | null;
      activityContent: string;
      sessionEndTime: null;
      activityLabelTag: null;
      activityName: string;
      sessionStartTime: null;
      thematicList: Array<{
        canEnrollTotal: null;
        activityLabelDesc: string;
        enrollDeadLine: number;
        activityLabelTag: number;
        sites: Array<{
          siteId: number;
          siteName: string;
        }>;
        activityThematicId: number;
        activityThematicContent: string;
        durationDays: number;
        benefitLabelName: string[];
        enrollSource: number;
        salePromotionLabel: null;
        enrollStartAt: number;
        enrolledCount: number;
        startTime: number;
        endTime: number;
        activityLabelList: Array<{
          value: string;
          key: number;
        }>;
        activityThematicName: string;
      }>;
      autoAssignEndTime: null;
      autoAssignStartTime: null;
      benefitLabelName: string[];
      sessionList: null;
      sessionAssignType: number;
      sessionAggList: null;
      activityType: number;
    }>;
  };
}
export async function getActivityList<T = GetActivityListResult>({ mallId }: { mallId: number }) {
  return request<T, T>({
    url: `https://agentseller.temu.com/api/kiana/gamblers/marketing/enroll/activity/list`,
    method: 'POST',
    data: {
      needCanEnrollCn: true,
    },
    headers: {
      Mallid: mallId,
    },
  });
}

// 获取活动中产品的因建议报价和建议库存的信息
// rowCount 最大支持是 50
export interface GetActivityProducInfotListResult {
  success: boolean;
  // 1000000 表示成功
  errorCode: number;
  errorMsg: null | string;
  result: {
    hasMore: boolean;
    matchList: Array<{
      activitySiteInfoList: Array<{
        mustPrivilege: boolean;
        skcList: Array<{
          salesLabelList: number[];
          skcId: number;
          dailyPrice: number | null;
          skuList: Array<{
            dailyPrice: number;
            activityPrice: number | null;
            extCode: string;
            // 建议活动价格
            suggestActivityPrice: number;
            currency: string;
            privilegeSuggestActivityPrice: number;
            extAttr: any;
            activityDiscount: number | null;
            suggestActivityDiscount: number | null;
            skuId: number;
            properties: Record<string, string>;
          }>;
          color: string | null;
          privilegeSuggestActivityPrice: number | null;
          extAttr: any;
          suggestActivityDiscount: number | null;
          activityPrice: number | null;
          extCode: string;
          suggestActivityPrice: number | null;
          currency: string | null;
          activityDiscount: number | null;
          properties: Record<string, string>;
        }>;
        siteId: number;
        siteName: string;
      }>;
      targetActivityStock: number;
      productId: number;
      activityProductExtVO: {
        hasSameStyleSkuIdList: number[];
        highPriceTag: number;
      };
      groupId: number | null;
      pictureUrl: string;
      canEnrollSessionCount: number;
      hasPrivilege: any; // 原始数据为null，无法确定类型
      sites: Array<{
        siteId: number;
        siteName: string;
      }>;
      isApparel: number;
      productName: string;
      goodsExtAttr: {
        semiDrCode: string;
      };
      salesStock: number;
      // 建议活动库存
      suggestActivityStock: number;
      activityExtAttr: {
        lowSoldScore: boolean;
      };
      isHotProduct: boolean;
      enrollSessionIdList: number[];
      suggestEnrollSessionIdList: number[];
      estimatedIncrease: any; // 原始数据为null，无法确定类型
      currency: string;
      refuseActivityLimit: any; // 原始数据为null，无法确定类型
    }>;
    searchScrollContext: string;
    stillCount: number;
  };
}

// {
//     "activityType": 13,
//     "activityThematicId": 2506170901964401,
//     "rowCount": 50,
//     "addSite": true
// }

export interface GetActivityProductInfoListOptions {
  activityType: number;
  activityThematicId?: number;
  rowCount?: number;
  addSite?: boolean;
  searchScrollContext?: string;
  mallId: number;
}

// '{"total":3104,"scrollCount":100,"scrollContext":{"sortStr":"{\\"sort\\":[{\\"product_id\\":{\\"order\\":\\"desc\\"}}]}","contextArgName":"scrollContext","sortValues":[9487315062]},"hasMore":true,"stillCount":3004}'
export async function getActivityProductInfoList<T = GetActivityProducInfotListResult>({
  activityThematicId,
  activityType,
  rowCount,
  addSite,
  searchScrollContext,
  mallId,
}: GetActivityProductInfoListOptions) {
  const data: Omit<GetActivityProductInfoListOptions, 'mallId'> = {
    activityType: activityType,
    rowCount: rowCount || 50,
    addSite: addSite || true,
  };
  if (activityThematicId) {
    data.activityThematicId = activityThematicId;
  }
  if (searchScrollContext) {
    data.searchScrollContext = searchScrollContext;
  }
  return request<T, T>({
    url: `https://agentseller.temu.com/api/kiana/gamblers/marketing/enroll/semi/scroll/match`,
    method: 'POST',
    data: data,
    headers: {
      Mallid: mallId,
    },
  });
}

// 获取报名场次信息
// productIds 的最大数量是 200
// productIds 不能为空,否则 3000000 为错误码
interface ActivitySession {
  startDateStr: string;
  sessionName: string;
  sessionStatus: number;
  subPromotionType: number;
  siteName: string;
  sessionId: number;
  durationDays: number;
  sessionFailReason: null;
  siteId: number;
  startTime: number;
  endTime: number;
  endDateStr: string;
}
export interface GetActivitySessionListResult {
  success: boolean;
  errorCode: number;
  errorMsg: null | string;
  result: {
    siteIds: number[];
    list: ActivitySession[];
    productCanEnrollSessionMap: {
      [productId: string]: ActivitySession[];
    };
  };
}

export interface GetActivitySessionListOptions {
  activityType: number;
  activityThematicId?: number;
  productIds: number[];
  mallId: number;
}
export async function getActivitySessionList<T = GetActivitySessionListResult>({
  activityType,
  activityThematicId,
  productIds,
  mallId,
}: GetActivitySessionListOptions) {
  const data: Omit<GetActivitySessionListOptions, 'mallId'> = {
    activityType: activityType,
    productIds,
  };
  if (activityThematicId) {
    data.activityThematicId = activityThematicId;
  }
  return request<T, T>({
    url: `https://agentseller.temu.com/api/kiana/gamblers/marketing/enroll/session/list`,
    method: 'POST',
    data: data,
    headers: {
      Mallid: mallId,
    },
  });
}

// 进行活动报名
export interface RegidtrationProductActivityResult {
  success: boolean;
  errorCode: number;
  errorMsg: null | string;
  result: {
    lowStockProductIdList: null;
    failCount: number;
    successCount: number;
    product2SiteEnrollResultMap: Record<string, any>; // 或更具体的类型
    failList: Array<{
      productId: number;
      failMsg: string;
      failReason: number;
      failEnum: string;
    }>;
    productId2EnrollIdMap: Record<string, any>;
  };
}

export interface RegidtrationProductActivityOptions {
  activityType: number;
  activityThematicId?: number;
  productId: number;
  activityStock: number;
  mallId: number;
  siteId: number;
  skcId: number;
  skuId: number;
  activityPrice: number;
  sessionIds: number[];
}
export async function submitRegidtrationProductActivity<T = RegidtrationProductActivityResult>({
  activityType,
  activityThematicId,
  productId,
  activityStock,
  mallId,
  siteId,
  skcId,
  skuId,
  activityPrice,
  sessionIds,
}: RegidtrationProductActivityOptions) {
  const data = {
    activityType: activityType,
    productList: [
      {
        productId: productId,
        activityStock: activityStock,
        siteInfoList: [
          {
            siteId: siteId,
            skcList: [
              {
                skcId: skcId,
                skuList: [
                  {
                    skuId: skuId,
                    activityPrice: activityPrice,
                  },
                ],
              },
            ],
          },
        ],
        sessionIds: sessionIds,
      },
    ],
  } as any;
  if (activityThematicId) {
    data.activityThematicId = activityThematicId;
  }
  return request<T, T>({
    url: `https://agentseller.temu.com/api/kiana/gamblers/marketing/enroll/semi/submit`,
    method: 'POST',
    data: data,
    headers: {
      Mallid: mallId,
    },
  });
}
